package project;

import oracle.kv.*;

/**
 * la classe initialisation de la base de donnee du etape 1 b
 */
public class Init_1_b {

	// numbre de item dans chaque store
	public static final int storeSize = 500;
	// nombre de store
	public static final int N = 1000 / storeSize;
	public static KVStore[] stores;

	/**
	 * Runs Init
	 */
	public static void main(String args[]) {
		try {
			Init_1_b application = new Init_1_b();
			application.init();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Initialisation des Kvstore
	 * 
	 * Nous pouvons creer N store et les configurer, ici, nous configurons
	 * seulement 2 stores.
	 * 
	 * */
	private Init_1_b() {

		String[] storeNames = new String[N];
		storeNames[0] = "kvstore";
		storeNames[1] = "kvstore";
		String[] hostNames = new String[N];
		hostNames[0] = "ari-31-312-14";
		hostNames[1] = "ari-31-312-15";
		String[] hostPorts = new String[N];
		hostPorts[0] = "5000";
		hostPorts[1] = "5000";

		// configurer N kvstore
		stores = new KVStore[N];
		for (int i = 0; i < N; i++) {
			stores[i] = KVStoreFactory.getStore(new KVStoreConfig(
					storeNames[i], hostNames[i] + ":" + hostPorts[i]));
		}
	}

	/**
	 * Initialisation des produits.
	 * */
	public void init() {
		for (int i = 1; i <= 1000; i++) {
			Key key = Key.createKey("P" + i, "quality");
			// obtenir l'index de store par la fonction de hachage.
			int indexStore = hachage(i);
			String data = "0";
			Value value = Value.createValue(data.getBytes());
			// stocker dans le kvstore specifique
			stores[indexStore].put(key, value);
		}
		Key k1 = Key.createKey("P" + 500, "quality");
		// Test - start
		int indexStore = hachage(500);
		System.out.println(indexStore);
		ValueVersion valueVersion = stores[indexStore].get(k1);
		System.out.println(k1.toString() + " "
				+ new String(valueVersion.getValue().getValue()));
		// Test - end
		for (int i = 0; i < N; i++)
			stores[i].close();
	}

	/**
	 * Fonction de hachage. On l'appelle pour obtenir l'index de store
	 * 
	 * @param i
	 *            cle de produit
	 * @return l'index de kvstore
	 * */
	public int hachage(int i) {
		int y = 0;
		if (i >= 0 && i <= 1000)
			y = (i - 1) / Init_1_b.storeSize;
		else
			y = -1;
		return y;
	}
}